package cn.springsecurity.demo.SecurityConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity (prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsServer userDetailsServer;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/sayhello/*").hasAnyRole("ADMIN")
                .antMatchers("/pop").hasAnyAuthority("AUTH_POP")
//                .antMatchers("/**").fullyAuthenticated()
//                .and().httpBasic()
                .and().logout()
                .and().rememberMe()
                .and().formLogin();

        http.rememberMe();
    }

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
//        auth.inMemoryAuthentication().withUser("cc").password("698d51a19d8a121ce581499d7b701668").accountLocked(true).authorities();
        System.out.println("current this configure auto...");

        auth.userDetailsService(userDetailsServer).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return GetMD5(rawPassword.toString());
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                String tpwd = GetMD5(rawPassword.toString());
                if (tpwd.equals(encodedPassword))
                    return true;
                else
                    return false;
            }
        });
    }

    public static String GetMD5(String token)
    {
        String str=new String();
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            byte[] md5 = md.digest(token.getBytes());
            for(int i=0;i<16;i++)
            {
                String c=new String();
                c+=md5[i];
                int a=0;
                a= Integer.parseInt(c, 10);
                String s= Integer.toHexString(a);
                if(s.length()>2)
                    str+=s.substring(s.length()-2);
                else if(s.length()==1)
                    str+="0"+s;
                else
                    str+=s;
            }
            System.out.println(str);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return str;
    }
}
